// const http = require('http')
// const serve = http.createServer()
// serve.on('request', (req, res) => {
// 	res.writeHead(200, {
// 		"Content-Type": 'application/json'
// 	})
// 	res.end(
// 		JSON.stringify({
// 			data: 'hello world'
// 		})
// 	)
// })
// serve.listen(8000, () => {
// 	console.log('listen...');
// })

const updateTime = () => {
	this.timer = this.timer || setTimeout(() => this.time = new Date().toUTCString(), 5000);
	return this.time
}
const http = require('http');
const { uptime } = require('process');
http.createServer((req, res) => {
	const { url } = req
	if (url == '/') {
		res.end(`
			<html>
				Html Update Time ${updateTime()}
				<script src="main.js"></script>
			</html>
		`)
	} else if (url == '/main.js') {
		let content = `document.writeln('<br>JS Update Time:${updateTime()}')`
		// 强缓存
		//http1.0 Expires
		// res.setHeader('Expires', new Date(Date.now() + 10 * 1000).toUTCString())

		//http1.1 Cache-Control
		// res.setHeader('Cache-Control', 'max-age=20')

		// 协商缓存
		// last-modified && if-modified-since
		res.setHeader("Cache-Control", 'no-cache')
		// res.setHeader('last-modified', new Date().toUTCString())
		// if (new Date(req.headers['if-modified-since']).getTime() + 3 * 1000 > Date.now()) {
		// 	console.log('协商缓存命中');
		// 	res.statusCode = 304
		// 	res.end()
		// 	return
		// }

		//Etag && if-none-match 
		const crypto = require('crypto')
		const hash = crypto.createHash('sha1').update(content).digest('hex')
		res.setHeader('Etag', hash)
		if (req.headers['if-none-match'] === hash) {
			console.log('Etag 缓存命中');
			res.statusCode = 304
			res.end()
			return
		}
		res.statusCode = 200
		res.end(content)
	} else if (url == '/favicon.ico') {
		res.end('')
	}
})
	.listen(3000, () => {
		console.log('Http Cache Test at 3000');
	})
